package com.shs.sys.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shs.sys.common.ActiverUser;
import com.shs.sys.common.Constants;
import com.shs.sys.entity.Permission;
import com.shs.sys.entity.User;
import com.shs.sys.service.PermissionService;
import com.shs.sys.service.RoleService;
import com.shs.sys.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * @Author: jxm
 * @Description:
 * @Date: 2020/4/8 14:52
 * @Version: 1.0
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    @Lazy //只有使用的时候才会被加载
    private UserService userService;

    @Autowired
    @Lazy
    private RoleService roleService;

    @Autowired
    @Lazy
    private PermissionService permissionService;

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }
    /**
     *认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = token.getPrincipal().toString();
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("loginname",userName);
        User user = userService.getOne(queryWrapper);
        if(null!=user){
            ActiverUser activerUser = new ActiverUser();
            activerUser.setUser(user);
            //根据用户ID查询percode

            //1.查询所有菜单
            QueryWrapper<Permission> wrapper = new QueryWrapper<>();
            //设置只能查询权限
            wrapper.eq("type",Constants.TYPE_PERMISSION);
            wrapper.eq("available",Constants.AVAILABLE_TRUE);
            //2.根据用户ID+角色+权限去查询
            Integer userId = user.getId();
            //3.根据用户ID查询角色
            List<Integer> rids = roleService.queryUserRoleIdsByUid(userId);
            //4.根据角色id获取权限id
            Set<Integer> pids = new HashSet<>();
            for (Integer rid : rids) {
                List<Integer> permissionIds = roleService.queryRolePermissionIdsByRid(rid);
                pids.addAll(permissionIds);
            }
            List<Permission> list = new ArrayList<>();
            //5.根据角色id查询权限
            if(pids.size()>0){
                wrapper.in("id",pids);
                list = permissionService.list(wrapper);
            }
            List<String> percodes = new ArrayList<>();
            for (Permission permission : list) {
                percodes.add(permission.getPercode());
            }
            //放到
            activerUser.setPermissions(percodes);
            ByteSource bytes = ByteSource.Util.bytes(user.getSalt());
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activerUser,user.getPwd(),
                    bytes,this.getName());
            return info;
        }
        return null;
    }

    /**
     * 授权 --todo
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        ActiverUser activerUser = (ActiverUser) principalCollection.getPrimaryPrincipal();
        User user = activerUser.getUser();
        List<String> permissions = activerUser.getPermissions();
        if(user.getType()==Constants.USER_TYPE_SUPER){
            info.addStringPermission("*:*");
        }else{
            if(permissions.size()>0 && permissions!=null){
                info.addStringPermissions(permissions);
            }
        }
        return info;
    }
}
